/*
 *  Copyright 2012 Dirk Vranckaert
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package eu.vranckaert.vvl.activities.trafficinfo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.*;
import eu.vranckaert.vvl.R;
import eu.vranckaert.vvl.exception.ServiceException;
import eu.vranckaert.vvl.exception.webservice.WebServiceException;
import eu.vranckaert.vvl.exception.webservice.WebServiceRequestFailureException;
import eu.vranckaert.vvl.model.TrafficInfoGraphicalEnum;
import eu.vranckaert.vvl.service.InformationGraphicalService;
import eu.vranckaert.vvl.service.impl.InformationGraphicalServiceImpl;
import eu.vranckaert.vvl.utils.context.Constants;
import eu.vranckaert.vvl.utils.context.IntentUtil;
import eu.vranckaert.vvl.utils.context.NotificationUtil;
import eu.vranckaert.vvl.utils.context.Preference;

import java.util.Arrays;
import java.util.List;

/**
 * User: DIRK VRANCKAERT
 * Date: 16/02/12
 * Time: 12:12
 */
public class TrafficInfoGraphicalActivity extends Activity {
    private static final String LOG_TAG = TrafficInfoGraphicalActivity.class.getSimpleName();
    
    private InformationGraphicalService informationGraphicalService;
    
    private Button loadDataButton;
    private View loadingWheel;
    private View refreshButton;
    private Spinner spinner;
    private ImageView trafficImage;

    private List<TrafficInfoGraphicalEnum.Region> regionValues;

    private TrafficInfoGraphicalEnum.Region selectedRegion = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_traffic_info_graphical);

        createService();
        loadViewObjects();
        initializeView();
        attachButtons();
        
        handleAlarm(getIntent().getExtras());

        new LoadImageTask().execute();
    }

    private void handleAlarm(Bundle extras) {
        if (extras == null)
            return;

        Object o = extras.get(Constants.Extra.REGION);
        if (o != null) {
            TrafficInfoGraphicalEnum.Region region = (TrafficInfoGraphicalEnum.Region) o;
            selectedRegion = region;
            spinner.setSelection(regionValues.indexOf(selectedRegion));

            NotificationUtil.getInstance(TrafficInfoGraphicalActivity.this).flashLedLight();
        }
    }

    private void createService() {
        informationGraphicalService = new InformationGraphicalServiceImpl(TrafficInfoGraphicalActivity.this);
    }

    private void loadViewObjects() {
        loadDataButton = (Button) findViewById(R.id.load_info_button);
        loadingWheel = findViewById(R.id.progress_indicator_container);
        refreshButton = findViewById(R.id.refresh_button_container);
        spinner = (Spinner) findViewById(R.id.traffic_info_graphical_spinner_region);
        trafficImage = (ImageView) findViewById(R.id.traffic_info_image_view);
    }

    private void initializeView() {
        //Region list
        regionValues = Arrays.asList(TrafficInfoGraphicalEnum.Region.values());
        ArrayAdapter<CharSequence> dateRangeAdapter = ArrayAdapter.createFromResource(this,
                R.array.traffic_info_graphical_criteria_spinner_values_region, android.R.layout.simple_spinner_item);
        dateRangeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dateRangeAdapter);
        //Set the default value!
        selectedRegion = Preference.getSelectedGraphicalRegion(TrafficInfoGraphicalActivity.this);
        spinner.setSelection(regionValues.indexOf(selectedRegion));

        spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                selectedRegion = regionValues.get(pos);
                Preference.setSelectedGraphicalRegion(TrafficInfoGraphicalActivity.this, selectedRegion);
            }

            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    private void attachButtons() {
        loadDataButton.setOnClickListener(new SearchAllOnClickListener());
    }
    
    private class SearchAllOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            TextView validationTextView = (TextView) findViewById(R.id.validation);
            if (selectedRegion == null) {
                validationTextView.setVisibility(View.VISIBLE);
                return;
            }
            validationTextView.setVisibility(View.GONE);
            new LoadImageTask().execute();
        }
    }

    private class LoadImageTask extends AsyncTask<Void, Void, Bitmap> {
        private ServiceException exception = null;
        
        @Override
        protected void onPreExecute() {
            loadDataButton.setEnabled(false);
            refreshButton.setVisibility(View.GONE);
            loadingWheel.setVisibility(View.VISIBLE);
        }

        @Override
        protected Bitmap doInBackground(Void... voids) {
            try {
                return informationGraphicalService.getTrafficImage(selectedRegion);
            } catch (ServiceException e) {
                exception = e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            loadDataButton.setEnabled(true);

            if (bitmap == null) {
                if (exception instanceof WebServiceException) {
                    Toast.makeText(TrafficInfoGraphicalActivity.this, R.string.exception_general_web_service, Toast.LENGTH_LONG).show();
                } else if (exception instanceof WebServiceRequestFailureException) {
                    Toast.makeText(TrafficInfoGraphicalActivity.this, R.string.exception_web_service_request_failure, Toast.LENGTH_LONG).show();
                }
            } else {
                DisplayMetrics dm = new DisplayMetrics();
                TrafficInfoGraphicalActivity.this.getWindowManager().getDefaultDisplay().getMetrics(dm);
                int width = dm.widthPixels;
                int height = width * bitmap.getHeight() / bitmap.getWidth();
    
                trafficImage.setImageBitmap(bitmap);
                trafficImage.setLayoutParams(new LinearLayout.LayoutParams(width, height));

                trafficImage.setVisibility(View.VISIBLE);
            }

            loadingWheel.setVisibility(View.GONE);
            refreshButton.setVisibility(View.VISIBLE);
        }
    }

    public void onHomeClick(View view) {
        IntentUtil.goHome(this);
    }
    
    public void onRefreshClick(View view) {
        new LoadImageTask().execute();
    }
}
